<template>
	<view class="page">
		<view class="page">
			
			<!-- 消息弹窗 -->
			<quick-message ref="message"></quick-message>
			
			<view class="page-head" :style="{'marginTop': statusBarHeight+'px'}">
				<view class="page-head-left">
					<label class="iconfont iconzhadan"></label>
					<text class="bombsLength">{{bombs.length}}</text>
				</view>
				<view class="page-head-centre">
					<image class="userPic" :src="saolei.headPic ? saolei.headPic :'../../static/qq.jpeg'" mode="aspectFill"></image>
					<text class="percent">{{((complete/((colum*colum)-bombs.length))*100).toFixed(0)}}%</text>
					<text class="vs">VS</text>
					<text class="percent">{{opponetGrade}}%</text>
					<image class="userPic" :src="opponet.headPic ? opponet.headPic : '../../static/qq.jpeg'" mode="aspectFill"></image>
				</view>
				<view class="page-head-right">
					<label class="iconfont iconzhadan"></label>
					<text class="bombsLength">{{bombs.length}}</text>
				</view>
			</view>
			
			<view class="page-body">
				<movable-area style="background-color: #bebebe;overflow: hidden;">
					<!--  -->
					<movable-view
					:style="{
						'marginLeft': (screenWidth/2)-(16*colum) +'px',
						'marginTop': (screenHeight*5/12)-(16*colum)+'px',
						'width': (32*colum) +'px',
						'height': (32*colum) +'px',
					}"
					:direction="colum > 10 ? 'all' : ''"
					@scale="onScale" 
					scale 
					scale-min="0.8" 
					scale-max="2" 
					:scale-value="scale">
					
						<view
						class="page-block" 
						v-for="(i,index) in array" 
						:key=index
						@click="tap(index)"
						@longpress="flag(index)"
						style="border: 1px solid;"
						:style="{
							'width': 30 + 'px', 
							'height': 30 + 'px',
							'line-height': 30 + 'px',
							'backgroundColor': i.type == 'none' ? '#d8d8d8' : ' rgba(0,0,0,0)'
						}"
						>
							
							<image
							v-if="i.type == 'flag'"
							class="block-img"
							:style="{
								'width': 30 +'px',
								'height': 30 +'px',
								}"
							src="../../static/flag.png" 
							mode="">
							</image>
							
							<text v-if="i.type == 'none' && i.text == 0 "></text>		
							
							<image
							v-if="i.type == 'none' && i.text == '炸' "
							class="block-img"
							:style="{
								'width': 30 +'px',
								'height': 30 +'px',
								}"
							src="../../static/bomb.png" 
							mode="">
							</image>
							
							<text v-if="i.type == 'none' && i.text != '炸' && i.text != 0">{{i.text}}</text>
								
						</view>	
					</movable-view>
				</movable-area>
			</view>
			
			
			<view class="page-bottom">
				<view class="page-bottom-right">
					<button type="primary" @click="outRoom">退出房间</button>					
				</view>
			</view>
			
			<view v-if="!isBegin" class="waiting" :style="{
				'top': screenHeight/2-30 +'px',
				'left': screenWidth/2-80 +'px'
				}">
				等待对方同意中.......
			</view>
			
		</view>
	</view>
</template>

<script>
	
	import utils from '../../common/util.js'
	var _self
	
	var refuseTime = 0
	var agreeTime = 0
	var overTime = 0
	var successTime = 0
	var failTime = 0
	var runTime = 0
	
	
	export default {
		data() {
			return {
				screenHeight: uni.getSystemInfoSync().screenHeight,
				screenWidth: uni.getSystemInfoSync().screenWidth,
				statusBarHeight: uni.getSystemInfoSync().statusBarHeight,
				array: [], // 列表
				bombs: [], // 炸弹列表
				complete: 0, // 完成的个数
				opponetGrade: 0, // 对手成绩
				opponet:{} ,//对手资料 
				colum: 0, // 边长
				bombNumber: 0, // 炸弹数量
				isBegin: false, // 是否连接成功
				isFail: false, // 是否已经失败 进入查看状态
				scale: 1,
				time: 0,
				isLogin : false, // 是否登录
				saolei: {},
				message: {
					sender: "",
					receiver: "",
					content: '',
					sendTime: new Date().getTime(),
					type: '',
					heart: false
				},
				role: "" ,// 玩家角色
				timeId: "" //查询任务 
			}
		},
		onNavigationBarButtonTap(e) {},
		onLoad(da) {
			
			
			_self = this
			
			if(da.role == "receiver"){
				_self.role = "receiver"
				_self.isBegin = true
			}else{
				_self.role = "sender"
			}
			
			if(this.$store.state.opponet == null){
				uni.showToast({
					icon:"none",
					title:"跳转错误",
					position:"center"
				})
				uni.navigateBack({
					delta:1
				})
			}
			
			this.opponet = this.$store.state.opponet
			this.colum = this.$store.state.opponet.colum
			this.bombNumber = this.$store.state.opponet.bombNumber
			_self.message.receiver = this.$store.state.opponet.id
			
			var userInfo =  uni.getStorageSync("saolei_userInfo")
			if(userInfo){
				_self.saolei = userInfo
				_self.message.sender = userInfo.id
				_self.isLogin = true
			}else {
				uni.redirectTo({
					url:'../addAndRegister/addAndRegister',
					animationDuration:400,
					animationType:"slide-in-bottom"
				})
			}
			
			// 每1秒查一次对手是否离线
			var st = setInterval(function(){
				if(_self.isBegin){
					_self.getOpponetInfo()
				}
				
			},1000)
			_self.$store.commit("setOpponetTime",st)
			
			// 监听对方是否拒绝pk
			uni.$once('pk-refusePk',function(time){
				if(time != refuseTime){
					uni.showToast({
						icon:"none",
						title:"对方已拒绝",
						position:"center"
					})
					// 停止定时任务
					setTimeout(function(){
						uni.navigateBack({
							delta:2
						})
					},1000)
					refuseTime = time
				}
			})
			
			// 监听对方是否同意pk
			uni.$once('pk-agreePk',function(content,time){
				if(time != agreeTime){
					if(content == _self.$store.state.opponet.id){
						_self.isBegin = true
						uni.showToast({
							icon:"none",
							title:"连接成功",
							position:"center"
						})
					}else{
						uni.showToast({
							icon:"none",
							title:"非对手同意",
							position:"center"
						})
					}
					agreeTime = time
				}
				
			})
			
			
			// 监听对方是否超时
			uni.$once('pk-overTime',function(time){
				if(time != overTime){
					uni.showToast({
						icon:"none",
						title:"邀请已超时",
						position:"center"
					})
					setTimeout(function(){
						uni.navigateBack({
							delta:2
						})
					},1000)
					overTime = time
				}
				
			})
			
			
			// 挑战成功
			uni.$once('pk-success',function(time){
				if(time != successTime){
					// 停止定时任务
					_self.pkSuccess()
					successTime = time
				}
			})
			
			
			// 对手逃跑
			uni.$once('pk-run',function(time){
				if(time != runTime){
					// 停止定时任务
					_self.pkSuccess("对手逃跑,")
					runTime = time
				}
			})
			
			
			// 挑战失败
			uni.$once('pk-fail',function(time){
				if(time != failTime){
					// 停止定时任务
					_self.pkFail()
					failTime = time
				}
			})
			
			
			// 对手完成情况监听
			uni.$on('pk-message',function(data){
				_self.opponetGrade = data
			})
			
			this.$nextTick(function(){
				this.Init()
			})
			
			
		},
		onShow() {
			// 修改状态
			utils.setUserPkStatus("true")
			//打开webSocket
			// if(!_self.$store.state.start_timeId){
			// 	utils.connectSocketInit()
			// }
		},
		beforeDestroy() {
			_self.clearnTimeTask()
			// _self.pkFail()
		},
		methods: {
			Init(){
				_self.complete = 0
				_self.isFail = false
				
				this.bombs = utils.produceRandomNum(_self.bombNumber, (this.colum*this.colum-1))
				
				if(_self.role == "receiver"){
					// console.log(this.$store.state.pkInfo)
					var info = this.$store.state.pkInfo
					_self.bombNumber = info.bombNumber
					_self.bombs = info.bombs
					_self.colum = info.colum
					_self.array = []
					for (var i = 0; i < info.colum*info.colum; i++) {
						var item = {}
						item.type = 'shade' // 是否遮罩
						// 填充array
						if(info.bombs.indexOf(i) == -1){
							item.text = utils.calculateBombNumber(i,this.colum,this.bombs)
						}else{
							item.text = '炸'
						}
						_self.array.push(item)
					}
				}else{
					_self.array = []
					for (var i = 0; i < this.colum*this.colum; i++) {
						var item = {}
						item.type = 'shade' // 是否遮罩
						// item.text = i
						if(this.bombs.indexOf(i) == -1){
							item.text = utils.calculateBombNumber(i,this.colum,this.bombs)
						}else{
							item.text = '炸'
						}
						
						_self.array.push(item)
						
					}
					
					_self.message.type="pk_invite"
					_self.message.receiver = _self.opponet.id
					_self.message.content = JSON.stringify({
						bombs: _self.bombs,
						bombNumber: _self.bombNumber,
						colum: _self.colum
					})
					utils.send(_self.message)
				}
			},
			getOpponetInfo(){
				// 获取挑战对手资料
				uni.request({
					url: utils.basicUrl+"/saoleiUser/"+_self.opponet.id,
					method: "GET",
					data: {},
					success: function(res) {
						if(res.data.code === 20000){
							_self.opponet = res.data.data

							// console.log(res.data.data)
							if(_self.opponet.status == "离线"){
								uni.showToast({
									icon:"none",
									title:"对方离线，你赢了",
									position:"center"
								})
								// 停止定时任务
								_self.clearnTimeTask()
								// 扣对手的分
								uni.request({
									url: utils.basicUrl+'/saoleiUser/pkTotal/'+_self.opponet.id+"/"+(-1*parseInt(_self.colum)),
									method: "POST",
									data: {},
									success: function(res) {
										if(res.data.code === 20000){
										}else{
											_self.utils.requestFail(res)
											// uni.showToast({
											// 	icon:"none",
											// 	title: res.data,
											// 	position:"center"
											// })
										}
									},
									fail: () => {
										uni.showToast({
											icon:"none",
											title: '网络错误(￣▽￣)"',
											position:"center"
										})
									},
									complete() {
										
									}
								})
								// 加自己的分
								uni.request({
									url: utils.basicUrl+'/saoleiUser/pkTotal/'+_self.saolei.id+"/"+_self.colum,
									method: "POST",
									data: {},
									success: function(res) {
										if(res.data.code === 20000){
										}else{
											uni.showToast({
												icon:"none",
												title: res.data,
												position:"center"
											})
										}
									},
									fail: () => {
										uni.showToast({
											icon:"none",
											title: '网络错误(￣▽￣)"',
											position:"center"
										})
									},
									complete() {
										
									}
								})
								// 返回页面
								setTimeout(function(){
									uni.navigateBack({
										delta:1
									})
								},1000)
								
							}
						}else{
							_self.utils.requestFail(res)
							// uni.showToast({
							// 	icon:"none",
							// 	title: res.data,
							// 	position:"center"
							// })
						}
					},
					fail: () => {
						uni.showToast({
							icon:"none",
							title: '网络错误(｡・`ω´･)',
							position:"center"
						})
					},
					complete() {
						uni.hideLoading()
					}
				})
			},
			// 挑战成功
			pkSuccess(reason){
				_self.isBegin = false
				if(reason == undefined){
					reason = "恭喜你！"
				}
				_self.$store.commit("setOpponet",null)
				uni.request({
					url: utils.basicUrl+'/saoleiUser/pkTotal/'+_self.saolei.id+"/"+_self.colum,
					method: "POST",
					data: {},
					success: function(res) {
						if(res.data.code === 20000){
						}else{
							_self.utils.requestFail(res)
							// uni.showToast({
							// 	icon:"none",
							// 	title: res.data,
							// 	position:"center"
							// })
						}
					},
					fail: () => {
						uni.redirectTo({
							url:"../index/index"
						})
						uni.showToast({
							icon:"none",
							title: '网络错误(￣▽￣)"',
							position:"center"
						})
					},
					complete() {
						if(_self.role == "sender"){
							uni.navigateBack({
								delta:2
							})
						}else{
							uni.navigateBack({
								delta:1
							})
						}
					}
				})
				
				uni.showToast({
					icon:"none",
					title: reason + "挑战成功!",
					position:"center"
				})
				
				
			},
			// 挑战失败
			pkFail(reason){
				_self.isBegin = false
				if(reason == undefined){
					reason = "很遗憾"
				}
				
				_self.$store.commit("setOpponet",null)
				// 提交成绩
				uni.request({
					url: utils.basicUrl+'/saoleiUser/pkTotal/'+_self.saolei.id+"/"+(-1*parseInt(_self.colum)),
					method: "POST",
					data: {},
					success: function(res) {
						if(res.data.code === 20000){
						}else{
							_self.utils.requestFail(res)
							// uni.showToast({
							// 	icon:"none",
							// 	title: res.data,
							// 	position:"center"
							// })
						}
					},
					fail: () => {
						uni.showToast({
							icon:"none",
							title: '网络错误(￣▽￣)"',
							position:"center"
						})
					},
					complete() {
						if(_self.role == "sender"){
							uni.navigateBack({
								delta:2
							})
						}else{
							uni.navigateBack({
								delta:1
							})
						}
					}
				})
				uni.showToast({
					icon:"none",
					title:reason+"挑战失败！",
					position:"center"
				})
				
			},
			outRoom(){
				if(!_self.isFail && _self.isBegin){
					// 逃跑 发送失败消息
					uni.showModal({
						title:"警告",
						content:"中途逃跑算失败哦！",
						success: function (res) {
						    if (res.confirm) {
								_self.message.type = "pk_run_message"
								utils.send(_self.message)
								// 提交成绩
								uni.request({
									url: utils.basicUrl+'/saoleiUser/pkTotal/'+_self.saolei.id+"/"+(-1*parseInt(_self.colum)),
									method: "POST",
									data: {},
									success: function(res) {
										if(res.data.code === 20000){
										}else{
											_self.utils.requestFail(res)
											// uni.showToast({
											// 	icon:"none",
											// 	title: res.data,
											// 	position:"center"
											// })
										}
									},
									fail: () => {
										uni.showToast({
											icon:"none",
											title: '网络错误(￣▽￣)"',
											position:"center"
										})
									},
									complete() {
										if(_self.role == "sender"){
											uni.navigateBack({
												delta:2
											})
										}else{
											uni.navigateBack({
												delta:1
											})
										}
									}
								})
						    } 
						}
					})
					
				}else{
					console.log(_self.opponet.id)
					utils.cancelInvite(_self.opponet,new Date())
					setTimeout(function(){
						uni.navigateBack({
							delta:2
						})
					},500)
					
				}
			},
			clearnTimeTask(){
				clearInterval(_self.$store.state.opponetTimeId)
				_self.$store.commit("setOpponetTime",null)
			},
			onChange: function(e) {
				this.old.x = e.detail.x
				this.old.y = e.detail.y
			},
			onScale: function(e) {
				this.scale = e.detail.scale
				// this.old.scale = e.detail.scale
			},
			flag(id){
				if(_self.isFail){
					return
				}
				
				var item = this.array[id]
				if(item.type == 'none'){
					return
				}
				item.type = 'flag'
				this.array.splice(id,1,item)
			},
			
			tap(id){
				if(_self.isFail){
					return
				}
				
				if(!_self.isBegin){
					uni.showToast({
						icon:"none",
						title:"连接中....",
						position:"center"
					})
					return
				}
				
				var item = this.array[id]
				
				if(item.type == 'flag'){
					// 取消标记
					item.type = 'shade'
					this.array.splice(id,1,item)
					return
				}
				
				item.type = 'none'
				this.array.splice(id,1,item)
				_self.complete ++
				
				this.$nextTick(function(){
					if(item.text == "炸"){
						_self.array.forEach(ar => {
							ar.type = 'none'
						})
						
						_self.pkFail()
						
						// 发送失败消息
						_self.message.type = "pk_fail_message"
						utils.send(_self.message)
					}else if(item.text != 0 &&  _self.complete != _self.colum*_self.colum-_self.bombs.length){
						// 发送完成消息
						_self.message.type = "pk_message"
						_self.message.content = (_self.complete*100/(_self.colum*_self.colum-_self.bombs.length)).toFixed(2)
						utils.send(_self.message)
					}else if(item.text == 0 && _self.complete < _self.colum*_self.colum-_self.bombs.length){
						_self.clearZero(id)
					}else if(_self.complete == _self.colum*_self.colum-_self.bombs.length){
						// 发送成功消息
						_self.message.type = "pk_success_message"
						utils.send(_self.message)
						
						_self.pkSuccess()
						
					}
					
				})
			},
			
			// 批量清除为0的格子
			clearZero(i){
				
				if(_self.isFail){
					return
				}
				
				var target = []
				target.push(i)
				while(target.length > 0){
					// console.log(target)
					var id = parseInt(target.pop()) 
					var cl = parseInt(_self.colum)
					var flag = 0
					// 搜索8个方位角
					if( (id+1)%cl != 0 && (id+1) < cl*cl){
						if(_self.array[id+1].text == 0){
							if(_self.array[id+1].type == 'shade'){
								_self.array[id+1].type = 'none'
								target.push(id+1)
							}else{
								flag ++
							}
						}else{
							// 遇到边界了
							if(_self.array[id+1].type == 'shade' && _self.array[id+1].text != '炸'){
								_self.array[id+1].type = 'none'
								flag ++
							}else{
								// 遇到炸弹了
								flag ++
							}
						}
						
					}
					if( id-1 >= 0 && id%cl != 0){
						if(_self.array[id-1].text == 0){
							if(_self.array[id-1].type == 'shade'){
								_self.array[id-1].type = 'none'
								target.push(id-1)
							}else{
								flag ++
							}
						}else{
							// 遇到边界了
							if(_self.array[id-1].type == 'shade' && _self.array[id-1].text != '炸'){
								_self.array[id-1].type = 'none'
								flag ++
							}else{
								// 遇到炸弹了
								flag ++
							}
						}
					}
					if( id-cl >= 0){
						if(_self.array[id-cl].text == 0){
							if(_self.array[id-cl].type == 'shade'){
								_self.array[id-cl].type = 'none'
								target.push(id-cl)
							}else{
								flag ++
							}
						}else{
							// 遇到边界了
							if(_self.array[id-cl].type == 'shade' && _self.array[id-cl].text != '炸'){
								_self.array[id-cl].type = 'none'
								flag ++
							}else{
								// 遇到炸弹了
								flag ++
							}
						}
					}
					if( id-cl+1 >= 0 && (id-cl+1)%cl != 0){
						if(_self.array[id-cl+1].text == 0){
							if(_self.array[id-cl+1].type == 'shade'){
								_self.array[id-cl+1].type = 'none'
								target.push(id-cl+1)
							}else{
								flag ++
							}
						}else{
							// 遇到边界了
							if(_self.array[id-cl+1].type == 'shade' && _self.array[id-cl+1].text != '炸'){
								_self.array[id-cl+1].type = 'none'
								flag ++
							}else{
								// 遇到炸弹了
								flag ++
							}
						}
					}
					if( id-cl-1 >= 0 && (id-cl)%cl != 0){
						if(_self.array[id-cl-1].text == 0){
							if(_self.array[id-cl-1].type == 'shade'){
								_self.array[id-cl-1].type = 'none'
								target.push(id-cl-1)
							}else{
								flag ++
							}
						}else{
							// 遇到边界了
							if(_self.array[id-cl-1].type == 'shade' && _self.array[id-cl-1].text != '炸'){
								_self.array[id-cl-1].type = 'none'
								flag ++
							}else{
								// 遇到炸弹了
								flag ++
							}
						}
					}
					if( id+cl < cl*cl){
						if(_self.array[id+cl].text == 0){
							if(_self.array[id+cl].type == 'shade'){
								_self.array[id+cl].type = 'none'
								target.push(id+cl)
							}else{
								flag ++
							}
						}else{
							// 遇到边界了
							if(_self.array[id+cl].type == 'shade' && _self.array[id+cl].text != '炸'){
								_self.array[id+cl].type = 'none'
								flag ++
							}else{
								// 遇到炸弹了
								flag ++
							}
						}
					}
					if( id+cl+1 < cl*cl && (id+cl+1)%cl != 0){
						if(_self.array[id+cl+1].text == 0){
							if(_self.array[id+cl+1].type == 'shade'){
								_self.array[id+cl+1].type = 'none'
								target.push(id+cl+1)
							}else{
								flag ++
							}
						}else{
							// 遇到边界了
							if(_self.array[id+cl+1].type == 'shade' && _self.array[id+cl+1].text != '炸'){
								_self.array[id+cl+1].type = 'none'
								flag ++
							}else{
								// 遇到炸弹了
								flag ++
							}
						}
					}
					if( id+cl-1 < cl*cl && (id+cl)%cl != 0){
						if(_self.array[id+cl-1].text == 0){
							if(_self.array[id+cl-1].type == 'shade'){
								_self.array[id+cl-1].type = 'none'
								target.push(id+cl-1)
							}else{
								flag ++
							}
						}else{
							// 遇到边界了
							if(_self.array[id+cl-1].type == 'shade' && _self.array[id+cl-1].text != '炸'){
								_self.array[id+cl-1].type = 'none'
								flag ++
							}else{
								// 遇到炸弹了
								flag ++
							}
						}
					}
					
					if(flag == 8){
						// 8方均开
						var index = target.indexOf(id)
						target.splice(index,1)
					}
					
				}
				
				// 更新已完成的格子
				this.$nextTick(function(){
					_self.complete = 0
					_self.array.forEach(ar => {
						if(ar.type == 'none'){
							_self.complete ++
						}
					})
					
					// 判断是否胜利
					this.$nextTick(function(){
						if(_self.complete == _self.colum*_self.colum-_self.bombs.length){
							// 发送成功消息
							_self.message.type = "pk_success_message"
							utils.send(_self.message)
							_self.pkSuccess()
						}else{
							// 发送完成消息
							_self.message.type = "pk_message"
							_self.message.content = (_self.complete*100/(_self.colum*_self.colum-_self.bombs.length)).toFixed(2)
							utils.send(_self.message)
						}
					})
					
				})
				
			}
		
		}
	}
</script>

<style>
	@import url("pk.css");
</style>
